package site.timers.chat.util.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;

/**
 * @Classname GroupChatServer
 * @Description TODO
 * @Version 1.0.0
 * @Date 2025/8/12 14:47
 * @Author twl
 */
@Data
public class GroupChatServer {

    // 监听端口
    private int port;

    public GroupChatServer(int port) {
        this.port = port;
    }

    public ServerBootstrap run() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    //nio
                    .channel(NioServerSocketChannel.class)
                    //bossGroup,option,服务端接受连接的队列长度，如果队列已满，客户端连接将被拒绝。
                    .option(ChannelOption.SO_BACKLOG, 128)
                    //workerGroup,option,是否启动心跳包活机制
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new GroupChatServerChannelInitializer());
            //绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            System.out.println("服务器启动......");
            //监听关闭事件
            channelFuture.channel().closeFuture().sync();

            return serverBootstrap;
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw e;
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}


